"""
@name         超时检测
@version      1.0
@time         2025/04/06 16:52:49
@description  Retrieve data from the new in transit fault page of the TOP task operation management platform every 5 minutes, 
              and notify the middle desk personnel to urge the line supervisor for obstacles 
              that have not been responded to for more than 4 hours.
@author       liuYanXiang,652455342@qq.com
@match        https://133.96.90.208/
@Must-do      Fix DingDing roboot token and @-mentioned mobile number.
              The authorization may expire. If the acquisition fails, please update the authorization.9_Authorization.
"""

import requests
import json
from datetime import datetime
import time

regionManagerToMobile = {
    '固安县': '18603167524',
    '胜芳镇': '18603162465',
    '大城县': '18631628482',
    '文安县': '18631603172',
    '燕郊镇': '18603167045',
    '香河县': '18603167179',
    '三河市': '15531611098',
    '大厂回族自治县': '18603167239',
    '永清县': '18603167370',
    '广阳区': '18603169685',
    '安次区': '18633600080',
    '开发区': '18603167985',
    '霸州市': '18603164997',
    'admin': '18603168805',
    'MrLiu': '16633697996',
    'MrHe': '16633697909',
}

sent_toptaskids = set()
def get_authorization():
    try:
        with open('9_Authorization', 'r') as file:
            for line in file:
                if line:
                    return line
    except FileNotFoundError:
        print("9_Authorization file not found.")
    return None

def sendmessagetodingtalk(webhook_url, message, mobiles=[]):
    headers = {
        'Content-Type': 'application/json',
        'Charset': 'UTF-8'
    }

    payload = {
        'msgtype': 'text',
        'text': {
            'content': message
        },
        'at': {
            "atMobiles": mobiles,
            "isAtAll": False
        }
    }

    try:
        response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        result = response.json()
        if result.get('errcode') == 0:
            print('Message sent successfully.')
        else:
            print(f"Message sending failed, error message: {result.get('errmsg')}")
    except requests.RequestException as e:
        print(f'requests error: {e}')


def fetch_data():
    url = 'https://133.96.90.208/prod-api/top3/all_top_duty/get_allOrder_office_list'
    authorization = get_authorization()
    headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-encoding': 'gzip, deflate, br, zstd',
        'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'authorization': authorization,
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
    }
    params = {
        'grade': '',
        'breakdown_type': '',
        'top_task_id': '',
        'alarmTitle': '',
        'alarmCity': '',
        'alarmRegion': '',
       'speciality': '宽带群障',
       'startTime': '',
        'endTime': '',
        'grid_name': '',
        'neType': '',
        'objectLevel': '',
        'alarmVendor': '',
       'siteName': '',
       'secondSpeciality': '',
        'pageNum': 1,
        'pageSize': 100,
        'page': 1,
        'limit': 100
    }

    try:
        response = requests.post(url, headers=headers, params=params, verify=False, timeout=10)
        response.raise_for_status()
        data = json.loads(response.text)
        print(data)
        now = datetime.now()
        for row in data['officeRows']:
            toptaskid = row['topTaskId']
            sitename = row['siteName']
            alarmcity = row['alarmCity']
            tel = regionManagerToMobile[alarmcity]
            create_time_str = row['alarmCreateTime']
            create_time = datetime.strptime(create_time_str, '%Y-%m-%d %H:%M:%S')
            elapsed_time = now - create_time
            elapsed_hours = round(elapsed_time.total_seconds() / 3600, 2)
            print(elapsed_hours)
            if 4 < elapsed_hours < 6.0 and toptaskid not in sent_toptaskids:
                print(f"从 {create_time_str} 到现在用时: {elapsed_time}")
                message = f"工单临近超时通知-请通知相关人员\n单号：{toptaskid}\n位置:{alarmcity}\n历时:{elapsed_hours}小时\n线路主管电话:{tel}"
                sendmessagetodingtalk('https://oapi.dingtalk.com/robot/send?access_token=b48d67f748e84d15ccca047e932c6eb8de30f8f10c054909896d368af1e41368', message, ["16633697909"])
                sent_toptaskids.add(toptaskid)
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")


if __name__ == "__main__":
    while True:
        fetch_data()
        time.sleep(300)  # 暂停 300 秒（5 分钟）
    